package com.asiainfo.dacp.datastash.broker.flow.depend.service;

import java.util.Map;

import org.apache.commons.vfs2.FileObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.asiainfo.dacp.core.BeanFactory;
import com.asiainfo.dacp.datastash.broker.common.cache.BrokerContext;
import com.asiainfo.dacp.datastash.broker.core.BrokerException;
import com.asiainfo.dacp.datastash.broker.core.enums.ErrorCodeEnum;
import com.asiainfo.dacp.datastash.broker.flow.core.domain.Flow;
import com.asiainfo.dacp.metamodel.domain.ds.model.MetaDataSource;
import com.asiainfo.dacp.util.StringUtils;
import com.asiainfo.dacp.util.vfs.VfsUtils;
import com.google.common.base.Strings;

public class FileDependJudger implements DependJudger {
	private static Logger LOG = LoggerFactory.getLogger(FileDependJudger.class);
	private Map<String, Object> stepCfg;

	public FileDependJudger(Map<String, Object> stepCfg) {
		this.stepCfg = stepCfg;
	}

	@Override
	public boolean judge(Flow flow) throws BrokerException {
		String dsName = (String) stepCfg.get("dsName");
		String fileName = (String) stepCfg.get("stateExpr");

		if (Strings.isNullOrEmpty(fileName)|| Strings.isNullOrEmpty(dsName)) {
			LOG.error("文件依赖判断，缺少配置参数 stateExpr|dsName.");
			throw new BrokerException(ErrorCodeEnum.CONFIG_ERROR, "文件依赖判断，缺少配置参数 stateExpr|dsName");
		}

		BrokerContext context = BeanFactory.getBean(BrokerContext.class);
		MetaDataSource dataSource = context.getMetaDS(dsName);
		if(dataSource == null){
			String errMsg = String.format("文件依赖判断，未获取到指定数据源 dsName :%s", dsName);
			LOG.error(errMsg);
			throw new BrokerException(ErrorCodeEnum.CONFIG_ERROR, errMsg);
		}
		
		FileObject fileObject = null;
		try {
			fileName = dataSource.getVfsHeader() + StringUtils.variableSubstitution(fileName, flow.getUnit());
			fileObject = VfsUtils.getInstance().resolveFile(fileName);
			if (fileObject.exists()) {
				return true;
			} else {
			}
		} catch (Exception e) {
			LOG.error("文件依赖判断异常 .", e);
			throw new BrokerException(ErrorCodeEnum.CONFIG_ERROR, "文件依赖判断异常，" + e.getMessage());
		} finally {
			VfsUtils.getInstance().closeFileObject(fileObject);
		}
		return false;
	}

}
